<template>
	<view class="date-range-wrap">
		<view class="pb-flex-row pb-cross-center date-range">
			<view class="pb-expanded begin-date" :class="{'active':active == 1}" @click="beginClick">
				{{form.beginDay?form.beginDay:'开始日期'}}
			</view>
			<text style="margin: 0 20rpx;">-</text>
			<view class="pb-expanded end-date" :class="{'active': active == 2}" @click="endClick">
				{{form.endDay?form.endDay:'结束日期'}}
			</view>
		</view>

		<pb-picker-date ref="beginDatePicker" :date.sync="form.beginDay" :mode="mode" title="请选择开始日期" :maxDate="maxDate"
			@cancel="cancel">
		</pb-picker-date>
		<pb-picker-date ref="endDatePicker" :date.sync="form.endDay" :mode="mode" title="请选择结束日期" :minDate="minDate"
			:maxDate="today" @cancel="cancel"></pb-picker-date>
	</view>

</template>

<script>
	export default {
		name: "pb-picker-date-range",
		props: {
			mode: {
				type: String,
				default: "date", //date:年月日；year-month：年月
				require: false
			},
			formDate: {
				type: Object,
				default: () => {},
				require: false
			}
		},
		data() {
			return {
				active: null,
				//父组件传过来的对象要进行一次深拷贝，不然对其值进行watch监听时很容死循环
				form: JSON.parse(JSON.stringify(this.formDate)),
			};
		},
		watch: {
			'form.beginDay': function() {
				this.$emit('dateSelect', this.form)
			},
			'form.endDay': function() {
				this.$emit('dateSelect', this.form)
			},
		},
		computed: {
			today() {
				return (new Date().getTime())
			},
			maxDate() {
				const maxDate = this.form.endDay ? (new Date(this.form.endDay)).getTime() : new Date().getTime()
				return maxDate
			},
			minDate() {
				const minDate = this.form.beginDay ? (new Date(this.form.beginDay)).getTime() : 1325347200000
				return minDate
			},
		},
		methods: {
			beginClick() {
				this.$refs.beginDatePicker.show = true
				this.$refs.endDatePicker.show = false
				this.active = 1
			},
			endClick() {
				this.$refs.beginDatePicker.show = false
				this.$refs.endDatePicker.show = true
				this.active = 2
			},
			resetDate(beginDay, endDay) {
				this.active = null
				if (beginDay) {
					this.form.beginDay = beginDay
				} else {
					this.form.beginDay = null
				}
				if (endDay) {
					this.form.endDay = endDay
				} else {
					this.form.endDay = null
				}
			},
			cancel() {
				this.active = null
			}
		}
	}
</script>

<style lang="scss" scoped>
	.date-range-wrap {
		.date-range {
			padding: 32rpx 32rpx 0 32rpx;

			.begin-date,
			.end-date {
				height: 80rpx;
				line-height: 44rpx;
				text-align: center;
				padding: 18rpx 32rpx;
				box-sizing: border-box;
				color: #4D5566;
				background: #F2F3F5;
				border-radius: 8rpx;
			}

			.active {
				font-weight: 600;
				color: var(--uni-color-primary);
				border: 2rpx solid var(--uni-color-primary);
			}

		}
	}
</style>